'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: http.py
* @Time: 2025/11/5
* @All Rights Reserve By Brtc
'''
import logging
import os
from flask import Flask
from flask_cors import CORS
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_weaviate import FlaskWeaviate

from config.config import Config
from internal.exception.exception import CustomException
from internal.extension import redis_extension, celery_extension
from internal.extension.logging_extension import init_app
from internal.middleware.middleware import Middleware
from internal.router.router import Router
from pkg.response.http_code import HttpCode
from pkg.response.response import Response, json
from pkg.sqlalchemy import SQLAlchemy


class Http(Flask):
    """
    * @Author Leon-liao
    * @Function:Flask Http 类初始化函数
    * @Description //整个服务器的初始化都在这里
    * @Date :2025/11/5  14:29
    * @Param:
    """
    def __init__(self, *args,
                 config:Config,
                 db:SQLAlchemy,
                 weaviate:FlaskWeaviate,
                 migrate:Migrate,
                 router:Router,
                 login_manager:LoginManager,
                 middleware:Middleware,
                 **kwargs):
        """父类的初始化"""
        super().__init__(*args, **kwargs)
        """服务器的配置"""
        self.config.from_object(config)

        """日志模块初始化"""
        init_app(self)

        """路由的注册"""
        router.register_router(self)

        """跨域请求处理"""
        CORS(self,resources = {
            r"/*": {
                "origins": "*",
                "supports_credentials": True,
            }
        })
        """中间件注册"""
        login_manager.init_app(self)
        login_manager.request_loader(middleware.request_loader)

        """数据库初始化"""
        db.init_app(self)

        """向量数据库初始化"""
        weaviate.init_app(self)

        """初始化redis"""
        redis_extension.init_app(self)

        """数据库的迁移初始化"""
        migrate.init_app(self, db, directory="internal/migration")

        """异常处理注册"""
        self.register_error_handler(Exception, self._register_error_handler)

        """celery 异步协程启动"""
        celery_extension.init_app(self)


    def _register_error_handler(self, error:Exception):
        logging.error("异常:", str(error))
        if isinstance(error, CustomException):
            return json(Response(code=error.code, message=error.message, data=error.data if error.data is not None else {}))

        if os.getenv("FLASK_ENV") == "development":
            raise error
        else:
            return json(Response(code=HttpCode.FAIL, message=str(error), data={}))
